package spoon.support.builder;

import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import spoon.reflect.Factory;

import java.util.ArrayList;
import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: peter
* Date: 11/9/11
* Time: 11:44 AM
* To change this template use File | Settings | File Templates.
*/
class MyJDTCompiler extends JDTCompiler {

    private final String cp;

    public MyJDTCompiler(String cp) {
        this.cp = cp;
    }

    @Override
    public boolean compileSrc(Factory f, List<CtFile> files) throws Exception {
        if(files.isEmpty()) return true;
//		long t=System.currentTimeMillis();
        // Build input
        List<String> args = new ArrayList<String>();
        args.add("-1." + JAVA_COMPLIANCE);
        args.add("-preserveAllLocals");
        args.add("-enableJavadoc");
        args.add("-noExit");
        args.add("-proc:none");
        if (cp != null) {
            args.add("-classpath");
            args.add(cp);
        }
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(new DualClassLoader());
        String classLocation = getClass().getProtectionDomain().getCodeSource().getLocation().toString();
        // args.add("-nowarn");
        args.add(f.getEnvironment().getSourcePath());

//		JDTCompiler compiler = new JDTCompiler(new PrintWriter(System.out),
//				new PrintWriter(System.err));
        configure(args.toArray(new String[0]));
//		f.getEnvironment().debugMessage("compiling src: "+files);
        CompilationUnitDeclaration[] units = this.getUnits(files, f);
//		f.getEnvironment().debugMessage("got units in "+(System.currentTimeMillis()-t)+" ms");

        JDTTreeBuilder builder = new JDTTreeBuilder(f);

        for (CompilationUnitDeclaration unit : units) {
            try {
//				t=System.currentTimeMillis();
                unit.traverse(builder, unit.scope);
//				f.getEnvironment().debugMessage("built unit "+new String(unit.getMainTypeName())+" in "+(System.currentTimeMillis()-t)+" ms");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        Thread.currentThread().setContextClassLoader(contextClassLoader);
        return this.success;
    }
}
